package com.ProtocalAndUdp;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class XlsOperate {
	/**
	 * 将指定数据源设置到指定exl中
	 * @param fileName
	 * @param tableData
	 */
	public static void writeExcel(String fileName,List<List<String>> tableData)
    {
        WritableWorkbook wwb = null;
        try {
            //创建一个可写入的工作薄(Workbook)对象
            wwb = Workbook.createWorkbook(new File(fileName));
        } catch (IOException e){
            e.printStackTrace();
        }
        if (wwb != null){
            // 第一个参数是工作表的名称，第二个是工作表在工作薄中的位置
            WritableSheet ws = wwb.createSheet("sheet1", 0);
            try{
            	for(int i=0;i<tableData.size();i++){
            		List<String> row=tableData.get(i);
            		for(int j=0;i<row.size();j++){
            			Label lbl1 = new Label(j, i, row.get(j));
            			ws.addCell(lbl1);
            		}
            	}
            } catch (RowsExceededException e1){
                e1.printStackTrace();
            } catch (WriteException e1){
                e1.printStackTrace();
            }
            try{
                // 从内存中写入文件中
                wwb.write();
                wwb.close();
            } catch (IOException e){
                e.printStackTrace();
            } catch (WriteException e){
                e.printStackTrace();
            }
        }
    }

	/**
	 * 读取excel数据
	 * @param path
	 * @return
	 */
    public static List<List<String>> readExcel(String path)
    {
    	List<List<String>> table=new ArrayList<List<String>>();
        try{
            Workbook book = Workbook.getWorkbook(new File(path));
            Sheet sheet = book.getSheet(0);
            int x=sheet.getRows();
            int y=sheet.getColumns();
            //得到x行y列所在单元格的内容
            for(int i=0;i<x;i++){
            	List<String> row=new ArrayList<String>();
            	for(int j=0;j<y;j++){
            		row.add(sheet.getRow(x)[y].getContents());
            	}
            	table.add(row);
            }
        } catch (BiffException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        } 
        return table;
    }

}